package com.example.sunsg.okhttptest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Picture;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import com.breadtrip.R;
import com.example.sunsg.okhttptest.bean.CallBack;
import com.example.sunsg.okhttptest.bean.CompressImageTask;
import com.example.sunsg.okhttptest.qrcode.QRCodeHelper;
import com.example.sunsg.okhttptest.util.EncodeUtils;
import com.example.sunsg.okhttptest.util.ImageUtil;
import com.example.sunsg.okhttptest.util.SimpleAsyncTask;
import com.example.sunsg.okhttptest.util.StorageUtils;
import com.example.sunsg.okhttptest.Manager.ThreadPoolManager;
import com.example.sunsg.okhttptest.util.Util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class LongImageWebViewActivity extends ActionBarActivity {
    private WebView mWebView;
    /**
     * 没有图注的图片
     */
    private String noDescription = "<li> <img src = 'breadimage'> </li>";
    /**
     * 有图注的图片
     */
    private String imgStyle = "<li><img src='breadimage'><p>breadtrip_image_des</p></li>";
    private String qrCode = "<div class='product'><i></i><img src=''><p class='info'>长按识别二维码查看详情</p><p class='title font-ios-bold'>qrtitle</p></div>";

    private String qrCodeDarkStyle = "<div class='product'><img class='qrcode' src=''>"
            + "<div class='title'><p class='font-ios-bold'>qrtitle</p><i></i>" + "<div>长按识别二维码查看</div></div></div>";

    private String htmlData;


    private GestureDetector mGesture = null;

    private Button mBtnLongPic;

    private int count;
    private List<String> listTmep = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        mWebView = (WebView) findViewById(R.id.webview);
        mGesture = new GestureDetector(this, new GestureListener());
        mBtnLongPic = (Button) findViewById(R.id.btn_long_pic);
        mBtnLongPic.setOnClickListener(mOnClickListener);
        init();
        loadData();
    }

    private void init() {
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setDrawingCacheEnabled(true);
        // 启用支持javascript
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSaveFormData(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        String cacheDir = getDir("webCaCheDatabase", Context.MODE_PRIVATE).getPath();
        settings.setAppCacheMaxSize(1024 * 1024 * 20);
        settings.setAppCachePath(cacheDir);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        mWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mGesture.onTouchEvent(event);
            }
        });
    }

  public  static class Item {
       public String sourcePath;
       public String compressPath;

      public Item(String sourcePath,String compressPath) {
          this.sourcePath = sourcePath;
          this.compressPath = compressPath;
      }
  }


    /**
     * 加载数据
     */
    private void loadData() {
        new SimpleAsyncTask() {

            @Override
            public void preExcute() {

            }

            @Override
            public void doInBackground() {
                StringBuffer sb = new StringBuffer();

                String text = "";
                /** 星期 */
                String dateWeek = "";
                String datetime = "";
                String dateYears = "year";
                String dateMonth = "month";
                String dateDay = "day";

                String story_poi = "";
                List<String> list = new ArrayList<String>();
                list.add("/storage/emulated/0/DCIM/Camera/20150924_123842.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150924_123728.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150922_193500.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150803_194524.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150802_113605.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150802_113557.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150924_123842.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150924_123728.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150922_193500.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150803_194524.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150802_113605.jpg");
                list.add("/storage/emulated/0/DCIM/Camera/20150802_113557.jpg");

                ThreadPoolManager pool = ThreadPoolManager.getInstance();

                long startTime = System.currentTimeMillis();
                Log.i("test","starat time = "+startTime);
                count = list.size();
                for (int i = 0;i < list.size();i++){
                    pool.addTask(new CompressImageTask(new Item(list.get(i),""),callBack));

                }
                while (count >0){
//                    Log.i("test","count = "+count);
                }
                long stopTime = System.currentTimeMillis();
                Log.i("test","stop time = "+stopTime);
                Log.i("test","cha  time = "+(stopTime - startTime));

                for (String path : listTmep) {
//                    Log.i("test", "path.size = " + StorageUtils.getFileSize(path));
                    if (!TextUtils.isEmpty(path)) {
                        sb.append(noDescription.replace("breadimage", path));
                        Log.i("test","path != null " + path);
                    } else {
                        sb.append(imgStyle.replace("breadimage", path).replace("breadtrip_image_des",
                                "pathimage".replaceAll("\n", "<br>")));
                        Log.i("test", "path == null");
                    }

                }
                text = "三六九等发牢骚的肌肤";// 替换换行


                datetime = "16:30";
                dateWeek = "星期yi";

                dateYears = "2015";
                dateMonth = "10";
                dateDay = "19";
                story_poi = "三里屯soho";
                String url = "睡觉的房间电视剧风刀霜剑法律上的风景";
                String code = getQrCode(url);
                String defaultCover = "file:///android_asset/trip_default_cover.png";
                htmlData = Util.getFromAssets(getApplicationContext(), "life_story.html").replace("<breadtrip_story_image>", sb.toString())
                        .replace("breadtrip_story_text", text)
                        .replace("breadtrip_trip_cover", defaultCover)
                        .replaceAll("breadtrip_user_name", "sunsg")
                        .replace("tripname", "尚未分组的故事".replace("breadtrip_poi", story_poi)
                                .replace("<qrCode>", TextUtils.isEmpty(url) ? "" : code).replace("date_day", dateDay)
                                .replace("date_month_years", dateMonth + "." + dateYears).replace("<date_week_time>", dateWeek + " " + datetime));
            }

            @Override
            public void postExcute() {
                mWebView.loadDataWithBaseURL("file://" + Environment.getExternalStorageDirectory(), htmlData, "text/html", "UTF-8", null);
            }
        }.excute();
    }

    public Bitmap getBitmapWithMethod(int width,int height){

        Bitmap snapshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas bitmapCanvas = new Canvas(snapshot);
        mWebView.draw(bitmapCanvas);
        return snapshot;
    }


    private String getQrCode(String url) {
        if (!TextUtils.isEmpty(url)) {
            Bitmap bitmap = QRCodeHelper.getUrlQRCode(url, 800, R.color.color_5c5c5c,
                    Color.parseColor("#FFFFFF"));
            String qrcode = EncodeUtils.encodeBase64(ImageUtil.bmpToByteArray(bitmap, true));
            return qrCode.replace("lifeqrcode", qrcode).replace("qrtitle", "test");

        }
        return "";
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.btn_long_pic:
                    createLongPic();
                break;
            }
        }
    };

    private CallBack callBack = new CallBack() {
        @Override
        public void call(Object object) {
//            synchronized (this){
                count--;
                if(object instanceof  Item){
                    Item item = (Item) object;
                    if(TextUtils.isEmpty(item.compressPath)){
                        listTmep.add(item.sourcePath);
                    }else{
                        listTmep.add(item.compressPath);
                    }

                }
//            }
        }
    };

    /**
     * 截取长图
     */
    private void createLongPic(){
        mWebView.setFocusable(true);
//        mWebView.scrollTo(0, 0);
        mWebView.buildDrawingCache();
        final Picture picture = mWebView.capturePicture();
        final int height = picture.getHeight();
        final int width = mWebView.getWidth();
        new SimpleAsyncTask(){

            @Override
            public void preExcute() {
                Bitmap bitmap = null;
                try{
//                    bitmap = Bitmap.createBitmap(picture.getWidth(),picture.getHeight(), Bitmap.Config.RGB_565);
//                    Canvas canvas = new Canvas(bitmap);
//                    picture.draw(canvas);
                    bitmap = getBitmapWithMethod(width,height);
                }catch (OutOfMemoryError e){
                    if(bitmap != null && !bitmap.isRecycled()){
                        bitmap.recycle();
                    }
                }

                try {
                    FileOutputStream fos = new FileOutputStream(StorageUtils.mkdir() +"/long1.jpg");
                    bitmap.compress(Bitmap.CompressFormat.JPEG,80,fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(bitmap != null && !bitmap.isRecycled()){
                        bitmap.recycle();
                    }
                }
            }

            @Override
            public void doInBackground() {

            }

            @Override
            public void postExcute() {
                Log.i("test","long size = "+StorageUtils.getFileSize(StorageUtils.mkdir() +"/long1.jpg"));
            }
        }.excute();
    }


    /**
     * 手势处理类
     */
    class GestureListener extends GestureDetector.SimpleOnGestureListener {
        //点击
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            Log.i("test", "single");
            return super.onSingleTapUp(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Log.i("test", "onScroll");
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.i("test", "onFling");
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }


}
